package com.fangcun.service.api.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fangcun.bean.api.user.request.UserAddressListRequest;
import com.fangcun.bean.api.user.response.UserAddressListResponse;
import com.fangcun.common.canstant.ErrCode;
import com.fangcun.common.exception.ProAffairException;
import com.fangcun.common.exception.ProRunTimeException;
import com.fangcun.entity.UserReceivingAddress;
import com.fangcun.mapper.UserReceivingAddressMapper;
import com.fangcun.service.api.UserAddressService;

/**
 * @作者： 陳曉鬆 @时间： 2020年7月16日 - 上午9:40:58 @description：->
 */
@Service("userAddressService")
public class UserAddressServiceImpl implements UserAddressService {

	@Autowired
	private UserReceivingAddressMapper userReceivingAddressMapper;

	public static int DEFAULT_0 = 0;// 非默认
	public static int DEFAULT_1 = 1;// 默认

	@Override
	@Transactional
	public Long add(UserReceivingAddress address) throws ProAffairException {
		if (address.getIsDefault() == DEFAULT_1) {// 如果是默认的，那么先把这个用户的其他改为非默认的，然后在做添加
			userReceivingAddressMapper.updateDefaultByUserId(0, address.getUserId());
		}
		if (userReceivingAddressMapper.insertSelective(address) == 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "添加收获地址失败");
		}
		return address.getId();
	}

	@Override
	@Transactional
	public Long update(UserReceivingAddress address) throws ProAffairException {
		if (address.getIsDefault() == DEFAULT_1) {// 如果是默认的，那么先把这个用户的其他改为非默认的，然后在做添加
			userReceivingAddressMapper.updateDefaultByUserId(0, address.getUserId());
		}
		if (userReceivingAddressMapper.updateByPrimaryKeySelective(address) == 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "修改收获地址失败");
		}
		return address.getId();
	}

	@Override
	public List<UserAddressListResponse> list(UserAddressListRequest request) throws ProAffairException {
		List<UserAddressListResponse> list = userReceivingAddressMapper.listForApi(request);
		if (list == null || list.size() == 0) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return list;
	}

	@Override
	@Transactional
	public void delete(Long id) throws ProAffairException {
		if (userReceivingAddressMapper.deleteByPrimaryKey(id) == 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "删除收获地址失败");
		}
	}

}
